package com.micro.common.biz;



import com.micro.modual.model.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc 构建树工具类
 * @author LevelCoder
 * @version V1.0.0
 * @email LevelCoder@126.com
 * @date 2019/12/2
 */
public class TreeUtil {

    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object parentCode) {
        //定义树对象
        List<T> trees = new ArrayList<T>();
        //第一层遍历树节点
        for (T treeNode : treeNodes) {

            if (parentCode.toString().equals(treeNode.getParentCode())) {
                trees.add(treeNode);
            }
            //第二层遍历
            for (T it : treeNodes) {
                if (it.getParentCode().equals(treeNode.getCode())) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<TreeNode>());
                    }
                    treeNode.add(it);
                }
            }
        }
        return trees;
    }


    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes,Object parentCode) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (parentCode.equals(treeNode.getParentCode())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getCode() == it.getParentCode()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }


}
